/** Helper to allow imports from this file. */
function include(filename) {
  var head = document.getElementsByTagName('head')[0];
  script = document.createElement('script');
  script.src = filename;
  script.type = 'text/javascript';
  head.appendChild(script);
}

// general libs
include('lib/math3d.js');
include('lib/util.js');
include('lib/layout.js');

// level libs
include('lib/placemark.js');
include('lib/arrow-keys.js');
include('lib/course.js');
include('lib/move.js');
include('lib/car.js');
include('lib/flag.js');

// level defs
include('lib/levels.js');

google.load("earth", "1");
google.load("maps", "2.99");

var ge;
var geocoder;
var timeAtStartup;
var outText = '';

var earthLoaded = false;

function init() {
  geocoder = new google.maps.ClientGeocoder();
  // in util.js
  log('<span style="color:#999"><i>' +
      'Use log(string or number or object) to write ' +
      'output here</i></span>');
  // in layout.js
  resize();
  init3D();
  // in levels.js
  addLevels();
}

// Init 'counter' (which is used to create unique style IDs, for example)
var counter = 1;

function initCB(object) {
  var elapsedStartupTime = (new Date()).getTime() - timeAtStartup;
  ge = object;
  ge.getWindow().setVisibility(true);
  ge.getLayerRoot().enableLayerById(ge.LAYER_BUILDINGS, true);
  showVersions(ge);
  log('Startup time: ' + (elapsedStartupTime/1000) + 's');
}

function failureCB(message) {
  alert('Plugin load failed: ' + message);
}

function init3D() {
  timeAtStartup = (new Date()).getTime();
  google.earth.createInstance("map3d", initCB, failureCB);
}

function showViewControls() {
  ge.getNavigationControl().setVisibility(ge.VISIBILITY_SHOW);
}

function hideViewControls() {
  ge.getNavigationControl().setVisibility(ge.VISIBILITY_HIDE);
}

function runCode() {

  reset();

  // arrow-keys uses this to know if to capture key events.
  gameFocus = true;

  globalEval(unescapeXml(el("code").innerHTML) || el("code").value);void(0);
  // Sad but true.. can't just access evaled code immediately.
  setTimeout('runCode2()', 0);
}

function runCode2() {

  if (typeof(start) != 'undefined')
    start();
}

function reset() {
  clearPlacemarks();
  hideViewControls();
}

function showVersions(ge) {
  var pluginVersion = ge.getPluginVersion();
  var earthVersion = ge.getEarthVersion();

  var html;
  if (pluginVersion != earthVersion) {
    html = "WARNING: Plugin v.: " + pluginVersion + " != Earth v.:" + earthVersion;
  } else {
    html = "Version: " + pluginVersion;
  }
  log(html);
}
